import { ElNotification } from "element-plus"
import Clipboard from "clipboard"

function valueHandler(el, binding) {
	if (typeof binding.value == undefined) {
		binding.value = el.innerText
	}
	if (typeof binding.value === "string" || typeof binding.value === "number") {
		binding.value = {
			value: binding.value,
			success() {
				ElNotification({
					type: "success",
					title: "提示",
					message: "复制成功",
				})
			},
			error() {
				ElNotification({
					type: "error",
					title: "提示",
					message: "复制失败",
				})
			},
		}
	}
	return binding
}

export default {
	mounted: (el, bind) => {
		const binding = valueHandler(el, bind)

		const clipboard = new Clipboard(el, {
			text: () => binding.value.value + "",
		})
		el.__success_callback__ = binding.value.success
		el.__error_callback__ = binding.value.error
		clipboard.on("success", e => {
			el.__success_callback__ && el.__success_callback__(e)
		})
		clipboard.on("error", e => {
			el.__error_callback__ && el.__error_callback__(e)
		})
		el.__clipboard__ = clipboard
	},
	updated: (el, bind) => {
		const binding = valueHandler(el, bind)

		el.__clipboard__.text = () => binding.value.value
		el.__success_callback__ = binding.value.success
		el.__error_callback__ = binding.value.error
	},
	beforeUnmount: el => {
		el.__success_callback__ = null
		el.__error_callback__ = null
		el.__clipboard__.destroy()
		el.__clipboard__ = null
	},
}
